package com.aoip.telemetry.telemetry.configureui.business.order.cases.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.order.cases.mapper.OrderBaseMapper;
import com.aoip.telemetry.telemetry.configureui.business.order.cases.mapper.RelOrderElementMapper;
import com.aoip.telemetry.telemetry.configureui.business.order.cases.service.OrderCaseService;
import com.aoip.telemetry.telemetry.configureui.business.order.config.mapper.RelOrderStMapper;
import com.aoip.telemetry.telemetry.entity.order.OrderBaseEntity;
import com.aoip.telemetry.telemetry.entity.order.RelOrderElementEntity;
import com.aoip.telemetry.telemetry.entity.order.RelOrderStEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/2/22 16:52
 */
@Service
public class OrderCaseServiceImpl implements OrderCaseService {

    @Resource
    private OrderBaseMapper mapper;

    @Resource
    private RelOrderElementMapper relOrderElementMapper;

    @Resource
    private RelOrderStMapper relOrderStMapper;

    @Override
    public List<OrderBaseEntity> list(OrderBaseEntity entity) {
        QueryWrapper<OrderBaseEntity> queryWrapper = new QueryWrapper<>();
        String orderName = entity.getOrderName();
        String id = entity.getId();
        if (StringUtils.hasText(orderName)) {
            queryWrapper.like(true, "order_name", orderName);
        }
        if (StringUtils.hasText(id)) {
            queryWrapper.like(true, "id", id);
        }
        return mapper.selectList(queryWrapper);
    }

    @Override
    public OrderBaseEntity order(String id) {
        OrderBaseEntity orderBaseEntity = mapper.selectById(id);
        if (orderBaseEntity == null) {
            return new OrderBaseEntity();
        }
        QueryWrapper<RelOrderElementEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", id);
        queryWrapper.orderBy(true, true, "element_order");
        List<RelOrderElementEntity> elementEntityList = relOrderElementMapper.selectList(queryWrapper);
        QueryWrapper<RelOrderStEntity> orderStQueryWrapper = new QueryWrapper<>();
        orderStQueryWrapper.eq("order_id", id);
        List<RelOrderStEntity> relOrderStEntities = relOrderStMapper.selectList(orderStQueryWrapper);
        orderBaseEntity.setElementEntityList(elementEntityList);
        orderBaseEntity.setOrderStEntityList(relOrderStEntities);
        return orderBaseEntity;
    }

    @Override
    public int insert(OrderBaseEntity entity, List<RelOrderStEntity> relOrderSt) {
        String id = entity.getId();
        List<RelOrderElementEntity> existElementList = new ArrayList<>();
        if (StringUtils.hasText(id)) {
            QueryWrapper<RelOrderElementEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", id);
            existElementList = relOrderElementMapper.selectList(queryWrapper);
            mapper.updateById(entity);
        } else {
            mapper.insert(entity);
        }

        List<RelOrderElementEntity> elementEntityList = entity.getElementEntityList();
        List<String> delOrderElementIdList = new ArrayList<>();
        List<RelOrderElementEntity> updateList = new ArrayList<>();
        if (elementEntityList != null && elementEntityList.size() > 0) {
            Iterator<RelOrderElementEntity> iterator = elementEntityList.iterator();
            while (iterator.hasNext()) {
                RelOrderElementEntity next = iterator.next();
                Iterator<RelOrderElementEntity> elementIterator = existElementList.iterator();
                while (elementIterator.hasNext()) {
                    RelOrderElementEntity element = elementIterator.next();
                    if (element.getId().equals(next.getId())) {
                        updateList.add(next);
                        iterator.remove();
                        elementIterator.remove();
                    }
                }
            }
            if (elementEntityList.size() > 0) {
                elementEntityList.forEach(item -> {
                    item.setOrderId(entity.getId());
                    relOrderElementMapper.insert(item);
                });
            }
            if (updateList.size() > 0) {
                updateList.forEach(item -> relOrderElementMapper.updateById(item));
            }
        }
        if (existElementList != null && existElementList.size() > 0) {
            existElementList.forEach(item -> delOrderElementIdList.add(item.getId()));
            if (delOrderElementIdList.size() > 0) {
                relOrderElementMapper.deleteBatchIds(delOrderElementIdList);
            }
            return existElementList.size() + 1;
        }
        saveRelOrderSt(entity, relOrderSt);
        return 1;
    }

    /**
     * 更新指令与测站关联关系表
     *
     * @param entity     指令实例实体
     * @param relOrderSt 指令与测站关联关系
     * @author chenbai
     * @date 2022/2/23
     **/
    private void saveRelOrderSt(OrderBaseEntity entity, List<RelOrderStEntity> relOrderSt) {
        String id = entity.getId();
        QueryWrapper<RelOrderStEntity> relOrderStQueryWrapper = new QueryWrapper<>();
        relOrderStQueryWrapper.eq("order_id", id);
        List<RelOrderStEntity> relOrderStList = relOrderStMapper.selectList(relOrderStQueryWrapper);
        if (relOrderSt != null && relOrderSt.size() > 0) {
            if (relOrderStList != null && relOrderStList.size() > 0) {
                Iterator<RelOrderStEntity> iterator = relOrderSt.iterator();
                while (iterator.hasNext()) {
                    RelOrderStEntity next = iterator.next();
                    Iterator<RelOrderStEntity> orderStIterator = relOrderStList.iterator();
                    while (orderStIterator.hasNext()) {
                        RelOrderStEntity orderSt = orderStIterator.next();
                        if (orderSt.getStCode().equals(next.getStCode())) {
                            iterator.remove();
                            orderStIterator.remove();
                        }
                    }
                }
            }
            //除掉数据库已存在指令与测站关联关系后，还需新增的关联关系数据
            if (relOrderSt.size() > 0) {
                relOrderSt.forEach(item -> relOrderStMapper.insert(item));
            }
        }
        //除掉用户输入与数据库存在指令与测站关联关系后，还需删除的关联关系数据
        if (relOrderStList != null && relOrderStList.size() > 0) {
            List<String> ids = relOrderStList.stream().map(RelOrderStEntity::getId).collect(Collectors.toList());
            relOrderStMapper.deleteBatchIds(ids);
        }
    }

    @Override
    public int update(OrderBaseEntity entity, List<RelOrderStEntity> relOrderSt) {
        return insert(entity, relOrderSt);
    }

    @Override
    public void delete(long[] ids) {
        for (long id : ids) {
            mapper.deleteById(id);
            Map<String, Object> columnMap = new HashMap<>(1);
            columnMap.put("order_id", id);
            relOrderElementMapper.deleteByMap(columnMap);
        }

    }
}
